﻿Imports System.Activities
Imports System.Data.SqlClient
Imports System.Activities.Presentation.Metadata
Imports System.ComponentModel
Imports System.Drawing
Imports System.Activities.Expressions
Imports System.Activities.Presentation.PropertyEditing

Public Class BackUpActivity
    Inherits MSSQLBaseActivity

    Public Property DatabaseName As InArgument(Of String)
    Public Property OutputTarget As InArgument(Of String)
    Public Property BackUpTarget As InArgument(Of String) = "DATABASE"

    Public Sub New()
        Me.DisplayName = My.Resources.BackupActivityDisplayName
    End Sub

    Protected Overrides Sub CacheMetadata(metadata As System.Activities.CodeActivityMetadata)
        MyBase.CacheMetadata(metadata)

        Dim backupArgLiteral = TryCast(Me.BackUpTarget.Expression, Literal(Of String))
        If backupArgLiteral IsNot Nothing Then
            Dim backupVal = backupArgLiteral.Value
            If Not (New ValidationTypeStrings).CheckTypeStrings(backupVal) Then
                metadata.AddValidationError(My.Resources.ValidTypeStringError)
            End If
        End If

    End Sub

    Protected Overrides Function BeginExecute(context As System.Activities.AsyncCodeActivityContext, callback As System.AsyncCallback, state As Object) As System.IAsyncResult
        Dim dbname = context.GetValue(Me.DatabaseName)
        Dim output = context.GetValue(Me.OutputTarget)
        Dim backup = context.GetValue(Me.BackUpTarget)
        Dim conn = context.GetValue(Me.ConnectionStrings)
        Dim useLog = context.GetValue(Me.OutSQLLog)
        Dim asyncExecute = New asyncExecuteDelegate(AddressOf ExecuteSQL)
        context.UserState = asyncExecute

        Return asyncExecute.BeginInvoke(CreateSQLStrings(backup, dbname, output), conn, True, useLog, callback, state)
    End Function

    Public Overrides Sub Register()
        MyBase.Register()

        Dim build As New AttributeTableBuilder
        'ExecuteApplicationActivity Activity
        build.AddCustomAttributes(GetType(BackUpActivity),
                                              New ToolboxBitmapAttribute(GetType(BackUpActivity), "Backup.png"))
        build.AddCustomAttributes(GetType(BackUpActivity), "DatabaseName",
                                              New RequiredArgumentAttribute,
                                              New CategoryAttribute(My.Resources.CategoryDetail),
                                              New DisplayNameAttribute(My.Resources.DatabaseNameDisplay),
                                              New DescriptionAttribute(My.Resources.DatabaseNameDescription))
        build.AddCustomAttributes(GetType(BackUpActivity), "OutputTarget",
                                              New RequiredArgumentAttribute,
                                              New EditorAttribute(GetType(FilepathPropertyEditor), GetType(DialogPropertyValueEditor)),
                                              New CategoryAttribute(My.Resources.CategoryDetail),
                                              New DisplayNameAttribute(My.Resources.OutputTargetDisplay),
                                              New DescriptionAttribute(My.Resources.OutputTargetDescription))
        build.AddCustomAttributes(GetType(BackUpActivity), "BackUpTarget",
                                              New RequiredArgumentAttribute,
                                              New CategoryAttribute(My.Resources.CategoryDetail),
                                              New DisplayNameAttribute(My.Resources.BackupTypeDisplay),
                                              New DescriptionAttribute(My.Resources.BackupTypeDescription))

        MetadataStore.AddAttributeTable(build.CreateTable)
    End Sub

    Protected Overrides Function ExecuteSQL(script As String, connect As String, needRes As Boolean, ByVal needLog As Boolean) As System.Data.DataSet
        Dim sqlExec As New SQLExecute With {.Timeout = 0}
        sqlExec.ExecuteSQL(script, connect, needRes)

        Return sqlExec.ConvertMessageToDataset(sqlExec.InfoMessages)
    End Function

    ''' <summary>実行する SQL の生成</summary>
    ''' <remarks>http://msdn.microsoft.com/ja-jp/library/ms186865(SQL.90).aspx</remarks>
    Private Function CreateSQLStrings(ByVal backupType As String, ByVal dbname As String, ByVal output As String) As String
        Dim setFilePath As Boolean = False
        If output.Contains("\") OrElse output.Contains(":") OrElse
            output.Contains("/") OrElse output.Contains(".") Then setFilePath = True
        Dim sqlBuilder As New System.Text.StringBuilder
        With sqlBuilder
            .Append("BACKUP ")
            .Append(backupType.ToUpper + " ")
            .Append(dbname + " ")
            .Append("TO ")
            If setFilePath Then .Append("DISK='")
            .Append(output)
            If setFilePath Then .Append("'")
            .Append(";")
        End With
        Return sqlBuilder.ToString
    End Function
End Class
